package com.evil.common.oss.factory;

import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.oss.props.AliyunOssProperty;
import com.evil.common.oss.props.LocalOssProperty;
import com.evil.common.oss.service.AliyunOssFileStorageService;
import com.evil.common.oss.service.FileStorageService;
import com.evil.common.oss.service.LocalOssFileStorageService;

/**
 * @author liyang
 */
public class FileStorageServiceFactory {

    private static FileStorageService aliyunOssService;
    private static long aliyunOssCreatedTimestamp = 0;

    private static FileStorageService localOssService;
    private static long localOssCreatedTimestamp = 0;

    private static final long expireTimeInMillion = 60 * 5 * 1000L;

    public static FileStorageService build(Object property) {
        if (property instanceof AliyunOssProperty) {
            if (aliyunOssService != null && System.currentTimeMillis() - aliyunOssCreatedTimestamp < expireTimeInMillion) {
                return aliyunOssService;
            }
            aliyunOssService = new AliyunOssFileStorageService((AliyunOssProperty) property);
            aliyunOssCreatedTimestamp = System.currentTimeMillis();
            return aliyunOssService;
        }

        if (property instanceof LocalOssProperty) {
            if (localOssService != null && System.currentTimeMillis() - localOssCreatedTimestamp < expireTimeInMillion) {
                return localOssService;
            }
            localOssService = new LocalOssFileStorageService((LocalOssProperty) property);
            localOssCreatedTimestamp = System.currentTimeMillis();
            return localOssService;
        }

        throw new BusinessException(RCodeEnum.ERROR_FILE, "暂不支持该存储服务");
    }
}
